package com.wiserun.develop.apply.service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpSession;

import org.dozer.Mapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.wiserun.permission.entity.Role;
import com.wiserun.permission.entity.User;
import com.wiserun.permission.mapper.RoleMapper;
import com.wiserun.permission.mapper.UserMapper;
import com.wiserun.develop.apply.mapper.ApplyMapper;
import com.wiserun.develop.apply.model.Apply;
import com.wiserun.develop.apply.model.ApplyDTO;
import com.wiserun.develop.apply.model.ApplyListDTO;
import com.wiserun.develop.message.model.MessageDTO;
import com.wiserun.develop.message.service.MessageService;
import com.wiserun.develop.processconfig.model.ProcessConfig;
import com.wiserun.develop.processconfig.model.ProcessConfigDTO;
import com.wiserun.develop.processconfig.service.ProcessConfigService;
import com.wiserun.develop.processrecord.mapper.ProcessRecordMapper;
import com.wiserun.develop.processrecord.model.ProcessRecord;


@Service
public class ApplyService {
	@Autowired
    private Mapper mapperTrans;
	@Autowired
	private ApplyMapper mapper;
	@Autowired
	private MessageService mservice;
	@Autowired
	private HttpSession session;
	@Autowired
	private ProcessRecordMapper prmapper;
	@Autowired
	private ProcessConfigService pcservice;
	@Autowired
	private UserMapper Umapper;
	@Autowired
	private RoleMapper rmapper;

	/**
	 *可根据是否有条件查询所有资源的数据信息
	 *创建日期 2019-8-1
	 *liangbenjian 
	 */
	public List<ApplyListDTO> getPageList(ApplyDTO container){
		Apply applySearch= mapperTrans.map(container,Apply.class);	//封装数据到对象里
		Map<String, Object> map = new HashMap<>();
		String model=applySearch.getModel();
		String username=(String) session.getAttribute("user");
		String token=(String) session.getAttribute("token");
		 /*List<Role> roleList = rmapper.queryListByToken(token);
		 if(roleList.get(0).getRoleName().equalsIgnoreCase("租户")) {
			 map.put("Zphone", username);
		 }*/
			map.put("RA_Code", applySearch.getRA_Code());         //map中的key值与映射文件中的select语句#{}占位符中的值需要一一对应
			map.put("RA_CreateUser",applySearch.getRA_CreateUser());	
			map.put("LoginUser", username);
			map.put("model", model);
			map.put("user_token", token);
			map.put("RA_State",container.getRA_State());	
			if(container.getRA_State()!=null) {
			if(container.getRA_State().equals("A")) {
			map.put("RA_State_A", "1");
			}
			if(container.getRA_State().equals("B")) {
				map.put("RA_State_B", "1");
			}}
			map.put("RA_CreateTimeStart", applySearch.getRA_CreateTimeStart());	
			map.put("RA_CreateTimeEnd", applySearch.getRA_CreateTimeEnd());	
	        map.put("page", container.getCurrentPage());
	        map.put("size", container.getLimit());
/*	       System.out.println(map.get("model"));
	       System.out.println(map.get("LoginUser"));*/
	        List<Apply> applyList= mapper.queryPageList(map);            //将条件全部给方法得到查询出的数据
	        List<ApplyListDTO> list = new ArrayList<>();                     //放入list
	        for (Apply apply : applyList) {
	        	ApplyListDTO dto = mapperTrans.map(apply, ApplyListDTO.class);
	            list.add(dto);
	        }
			return list;	        
	}
	
	
	/**
	 *不分页查询统计数剧-导出用
	 *创建日期 2019-8-27
	 *liangbenjian 
	 */
	public List<ApplyListDTO> queryListexport(ApplyDTO container){
		Apply applySearch= mapperTrans.map(container,Apply.class);	//封装数据到对象里
		Map<String, Object> map = new HashMap<>();
		String model=applySearch.getModel();
		String username=(String) session.getAttribute("user");
		String token=(String) session.getAttribute("token");
			map.put("RA_Code", applySearch.getRA_Code());         //map中的key值与映射文件中的select语句#{}占位符中的值需要一一对应
			//这两个判断是初次进入页面查出来的值，如果是用户再次点击查询则传进来值在原来基础上再次查询
			map.put("RA_CreateUser",applySearch.getRA_CreateUser());	
			map.put("LoginUser", username);
			map.put("model", model);
			map.put("user_token", token);
			map.put("RA_State",applySearch.getRA_State());		
			map.put("RA_CreateTimeStart", applySearch.getRA_CreateTimeStart());	
			map.put("RA_CreateTimeEnd", applySearch.getRA_CreateTimeEnd());	
	        map.put("page", container.getCurrentPage());
	        map.put("size", container.getLimit());
/*	       System.out.println(map.get("model"));
	       System.out.println(map.get("LoginUser"));*/
	        List<Apply> applyList= mapper.queryListexport(map);            //将条件全部给方法得到查询出的数据
	        List<ApplyListDTO> list = new ArrayList<>();                     //放入list
	        for (Apply apply : applyList) {
	        	ApplyListDTO dto = mapperTrans.map(apply, ApplyListDTO.class);
	            list.add(dto);
	        }
			return list;	        
	}
	/**
	 *可根据是否有条件查询所有工单的条数
	 *创建日期 2019-8-1
	 *liangbenjian 
	 */
	public Integer getTotal(ApplyDTO container) {
		Apply applySearch = mapperTrans.map(container, Apply.class);
		String username=(String) session.getAttribute("user");
		applySearch.setLoginUser(username);
        return mapper.queryCount(applySearch);
    }
	
	/**
	 *根据编号查询对应的一条详细数据
	 *创建日期 2019-7-30
	 *liangbenjian 
	 */
	public Apply getOne(ApplyDTO container) {
		System.out.println("--------------------------------------"+container.getRA_Code());
		Apply apply=mapper.queryOne1(container.getRA_Code());
		String u=apply.getRA_CreateUser();
		User u1=Umapper.queryOne2(u);
		apply.setCreateUserName(u1.getUserName());
		return apply;
	}
	/**
	 *根据编号查询对应的一条详细数据然后更新或者新增
	 *创建日期 2019-7-30
	 *liangbenjian 
	 */
	public Integer save(ApplyDTO container) {
		Apply apply;
		Date now = new Date(); 
		String username=(String) session.getAttribute("user");//拿到session里存储的登录人名字
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");//创建日期的格式
		SimpleDateFormat dateFormat1 = new SimpleDateFormat("yyyy/MM/dd HH/mm/ss");//编号
		String hehe = dateFormat.format(now);
		String code = dateFormat1.format(now);
		code=code.replaceAll("/","");
		code=code.replaceAll(" ","");
		int shu=(int) ((Math.random()*9+1)*10000);
		String s="SQ"+code+shu;
		apply = mapper.queryOne1(container.getRA_Code());
            if (apply == null) {
            	apply = new Apply();
            	session.setAttribute("RA_Code",s);
            	apply.setRA_Code(s);
            	apply.setRA_CreateTime(hehe);
            	apply.setRA_CreateUser(username);
            	apply.setRA_Batch("1");
            	if(container.getRA_Mark()!=null) {
            		apply.setRA_Mark(container.getRA_Mark());
            	}else {
            		apply.setRA_Mark("");
            	}
            	
            	apply.setRA_ApplyType(container.getRA_ApplyType());
            	apply.setRA_State("B0");
            	apply.setRA_UpdateTime(hehe);
            	apply.setRA_UpdateUser(username);
                return mapper.add(apply);
            }else {           	
/*            	String nowBatch=apply.getRA_Batch();
            	int nowBatch1=Integer.parseInt(nowBatch);
            	nowBatch1=nowBatch1+1;
            	String newBatch=nowBatch1+"";*/
            	session.setAttribute("RA_Code", container.getRA_Code());
            	apply.setRA_Batch(container.getRA_Batch());
            	apply.setRA_UpdateTime(hehe);
            	apply.setRA_UpdateUser(username);
            	apply.setRA_Code(container.getRA_Code());
            	apply.setRA_State(container.getRA_State());
            	apply.setRA_Mark(container.getRA_Mark());
            	apply.setRA_ApplyType(container.getRA_ApplyType());
                return mapper.update(apply);
            }        
    }
	/**
	 *提交操作，将状态改为A0
	 *创建日期 2019-8-1
	 *liangbenjian 
	 */
	public Integer submit(ApplyDTO container) {
		Apply apply;
		apply = mapper.queryOne1(container.getRA_Code());	
		System.out.println("----------------------------------提交"+apply.getRA_State());
			//生成通知消息
			MessageDTO m=new MessageDTO();
			m.setApplyCode(container.getRA_Code());
			m.setSM_Model("M1.1.1");
			m.setSM_Operate("提交");
			mservice.add(m);
			//流程批次+1
			String batch=apply.getRA_Batch();
			int b=Integer.parseInt(batch);
			b=b+1;
			String newB=b+"";
			apply.setRA_Batch(newB);
			//状态更新为A0
			apply.setRA_State("A0");
			//生成流程记录
			Date now = new Date(); 
			String username=(String) session.getAttribute("user");//拿到session里存储的登录人名字
			SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");//创建日期的格式
			String hehe = dateFormat.format(now);
			UUID uuid = UUID.randomUUID();
	        String strID = uuid.toString(); 
			ProcessRecord processRecord= new ProcessRecord();
			processRecord.setSPR_Code(strID);
			processRecord.setSPR_CreateTime(hehe);
			processRecord.setSPR_CreateUser(username);
			processRecord.setSPR_State("1");	
			processRecord.setSPR_Model("M1.1.1");
			processRecord.setSPR_ModelCode(container.getRA_Code());
			processRecord.setSPR_Action("提交");
			processRecord.setSPR_Result("Y");
			processRecord.setSPR_Batch(apply.getRA_Batch());
			//通过版本号和步骤编号查询到流程配置编号
			ProcessConfigDTO p=new ProcessConfigDTO();
		    p.setSPC_Step(apply.getRA_State());
		    /*p.setSPC_Version(apply.getRA_ApplyType());*/ 
		    //版本号暂时给一个固定版本号
		    p.setSPC_Version("1");
		    ProcessConfig pc= pcservice.getOne2(p);
		    processRecord.setSPR_ConfigNo(pc.getSPC_Code());
			prmapper.add(processRecord);
			return mapper.update(apply);				
	}

	
	/**
	 *根据编号拿到当前数据的状态执行人
	 *创建日期 2019-8-19
	 *liangbenjian 
	 */
	public List<Role> getRole(ApplyDTO container) {
		Apply apply=new Apply();
		List<Role> list= new ArrayList<>();
		apply=mapper.queryOne1(container.getRA_Code());
		ProcessConfigDTO pd=new ProcessConfigDTO();
		ProcessConfig pc=new ProcessConfig();
		/*pd.setSPC_Version(apply.getRA_ApplyType());*/
		//版本号暂时给一个固定版本号
		pd.setSPC_Version("1");
		pd.setSPC_Step(apply.getRA_State());
		String s=apply.getRA_State();
		if(s.equalsIgnoreCase("B1")||s.equalsIgnoreCase("B2")||s.equalsIgnoreCase("B3")||s.equalsIgnoreCase("B4")) {
			pd.setSPC_Step("B0");
		}
		if(s.equalsIgnoreCase("A4")) {
			 return list;
		}
		pc=pcservice.getOne2(pd);
		String role=pc.getSPC_Role();		
		if(role.indexOf(",")<0) {
			//不存在逗号，则为一人
			list.add(rmapper.queryOneByName(pc.getSPC_Role()));
		}else {
			 String[] newStr=role.split(","); 
			 List<String> l= Arrays.asList(newStr); 
			 for(int i=0;i<l.size();i++) {
				list.add(rmapper.queryOneByName(l.get(i)));
			 }
		}
        return list;
                   
    }
	
	/**
	 *根据编号拿到当前数据四审处理人
	 *创建日期 2019-8-23
	 *liangbenjian 
	 */
	public List<Role> getFourRole(ApplyDTO container) {
		Apply apply=new Apply();
		apply=mapper.queryOne1(container.getRA_Code());
		ProcessConfigDTO pd=new ProcessConfigDTO();
		ProcessConfig pc=new ProcessConfig();
		/*pd.setSPC_Version(apply.getRA_ApplyType());*/
		//版本号暂时给一个固定版本号
		pd.setSPC_Version("1");
		pd.setSPC_Step("A3");
		String s=apply.getRA_State();
		pc=pcservice.getOne2(pd);
		String role=pc.getSPC_Role();
		List<Role> list= new ArrayList<>();
		if(role.indexOf(",")<0) {
			//不存在逗号，则为一人
			list.add(rmapper.queryOneByName(pc.getSPC_Role()));
		}else {
			 String[] newStr=role.split(","); 
			 List<String> l= Arrays.asList(newStr);
			 for(int i=0;i<l.size();i++) {
				list.add(rmapper.queryOneByName(l.get(i)));
			 }
		}
        return list;
                   
    }
	
	
}
